﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;

namespace Isaac.Joy.Menu.Module
{
    /// <summary>
    /// 菜单类
    /// </summary>
    public class Menu : IMenu
    {
        /// <summary>
        /// 菜单名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 图标
        /// </summary>
        public string Icon { get; set; }

        /// <summary>
        /// 动作
        /// </summary>
        public MenuAction Action { get; set; }

        /// <summary>
        /// 是否为子节点
        /// </summary>
        public bool IsLeaf
        {
            get { return !Childrens.Any(); }
        }

        /// <summary>
        /// 排序编号
        /// </summary>
        public int Order { get; set; }

        /// <summary>
        /// 权限
        /// </summary>
        public string Permission { get; set; }


        /// <summary>
        /// 子菜单
        /// </summary>
        [XmlIgnore]
        public IEnumerable<IMenu> Childrens
        {
            get { return Menus; }
        }

        /// <summary>
        /// 子菜单，用于串行化xml文件
        /// </summary>
        public List<Menu> Menus { get; set; }

        /// <summary>
        /// 添加子菜单
        /// </summary>
        /// <param name="menu">子菜单</param>
        public void Add(IMenu menu)
        {
            if (Menus == null) return;

            var menuobj = menu as Menu;
            if(menuobj != null) Menus.Add(menuobj);
        }

        /// <summary>
        /// 重载比较方法，用于排序
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int CompareTo(object obj)
        {
            try
            {
                var menu = obj as IMenu;
                var result = menu != null && Order > menu.Order ? 0 : 1;
                return result;
            }
            catch (Exception) { return 0; }
        }
    }
}
